'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { api } from '@/lib/api'
import { IconLoader } from '@tabler/icons-react'
import useAuthStore from '@/stores/authStore'
import { UserVerificationLoading } from '@/components/AdvancedLoading'

interface AuthGuardProps {
  children: React.ReactNode
  fallback?: React.ReactNode
}

export default function AuthGuard({ children, fallback }: AuthGuardProps) {
  const router = useRouter()
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // 立即检查认证状态，无延迟
    const { token: storeToken } = useAuthStore.getState()
    const localToken = localStorage.getItem('auth_token')
    const userInfo = localStorage.getItem('user_info')
    const isLoggedInFlag = localStorage.getItem('isLoggedIn')

    const token = storeToken || localToken
    const hasValidAuth = (token && userInfo) || (isLoggedInFlag === 'true' && userInfo)

    if (!hasValidAuth) {
      setIsAuthenticated(false)
      setIsLoading(false)
      return
    }

    // 同步认证状态
    if (storeToken && !localToken) {
      localStorage.setItem('auth_token', storeToken)
    }
    if (localToken && !storeToken && userInfo) {
      try {
        const user = JSON.parse(userInfo)
        useAuthStore.getState().setLogin(localToken, user)
      } catch (e) {
        console.warn('[AuthGuard] 解析用户信息失败:', e)
      }
    }

    setIsAuthenticated(true)
    setIsLoading(false)
  }, [])

  // 处理未认证的跳转
  useEffect(() => {
    if (!isLoading && isAuthenticated === false) {
      router.push('/login')
    }
  }, [isLoading, isAuthenticated, router])

  // 正在加载中 - 直接返回 null，不显示任何加载界面
  if (isLoading) {
    return null
  }

  // 未认证 - 直接返回 null，跳转在useEffect中处理
  if (!isAuthenticated) {
    return null
  }

  // 已认证，显示受保护的内容
  return <>{children}</>
}

// 高阶组件版本
export function withAuthGuard<P extends {}>(
  Component: React.ComponentType<P>,
  fallback?: React.ReactNode
) {
  return function AuthenticatedComponent(props: P) {
    return (
      <AuthGuard fallback={fallback}>
        <Component {...props} />
      </AuthGuard>
    )
  }
} 